// pages/home/pages/create-goods/index.js
const {
    http
} = require('../../../../utils/apiutils.js');
import {
    input
} from '../../../../utils/tools'
const util = require("../../../../utils/util")
import {
    formatTime,
    formatTime1
} from '../../../../utils/util'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        xieyi: false,
        id:0,
        form: {
            id: '',
            title: '',
            beFrom: '1',
            place: '',
            content: '',
            contactPerson: '',
            telephoneNumber: '',
            lat: 0,
            lng: 0,
            endTime: '',
            images: ''
        },
        checked: true,
        showeditor: true,
        datetime: false,
        currentDate: new Date().getTime(),
        fileListImg: [],
        fileListImg1: [],
        img: [],
        img1: [],
        jobData:[]
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },
    showxieyi() {
        this.setData({
            xieyi: !this.data.xieyi
        })
    },
    onChange1(e) {
        this.setData({
            checked: e.detail
        })
    },
    editinput(e) {
        this.setData({
            content1: e.detail.html,
            content: e.detail.text,
        })
    },
    readOnlyChange() {
        this.setData({
            readOnly: !this.data.readOnly
        })
    },
    onLoad(options) {
        const platform = wx.getSystemInfoSync().platform
        const isIOS = platform === 'ios'
        this.setData({
            isIOS
        })
        const that = this
        this.updatePosition(0)
        let keyboardHeight = 0
        wx.onKeyboardHeightChange(res => {
            if (res.height === keyboardHeight) return
            const duration = res.height > 0 ? res.duration * 1000 : 0
            keyboardHeight = res.height
            console.log(res)
            setTimeout(() => {
                if (that.data.showeditor) return
                wx.pageScrollTo({
                    scrollTop: keyboardHeight,
                    success() {
                        that.updatePosition(keyboardHeight)
                        that.editorCtx.scrollIntoView()
                    }
                })
            }, duration)
        })
        if(options.id){
            this.setData({
                id:options.id
            })
            this.getDtl(options.id)
        }
    },
    updatePosition(keyboardHeight) {
        const toolbarHeight = 50
        const {
            windowHeight,
            platform
        } = wx.getSystemInfoSync()
        let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : 400
        this.setData({
            editorHeight,
            keyboardHeight
        })
    },
    calNavigationBarAndStatusBar() {
        const systemInfo = wx.getSystemInfoSync()
        const {
            statusBarHeight,
            platform
        } = systemInfo
        const isIOS = platform === 'ios'
        const navigationBarHeight = isIOS ? 44 : 48
        return statusBarHeight + navigationBarHeight
    },
    onEditorReady() {
        const that = this
        wx.createSelectorQuery().select('#editor').context(function (res) {
            that.editorCtx = res.context
            if(that.data.form.id){
                that.editorCtx.setContents({
                    html:that.data.form.content,
                    success(){
                        that.editorCtx.blur()
                    }
                })
            }
        }).exec()
    },
    format(e) {
        let {
            name,
            value
        } = e.target.dataset
        if (!name) return
        this.editorCtx.format(name, value)
    },
    onStatusChange(e) {
        const formats = e.detail
        this.setData({
            formats
        })
    },
    insertDivider() {
        this.editorCtx.insertDivider({
            success: function () {
                
            }
        })
    },
    clear() {
        this.editorCtx.clear({
            success: function (res) {
                console.log("clear success")
            }
        })
    },
    removeFormat() {
        this.editorCtx.removeFormat()
    },
    insertDate() {
        const date = new Date()
        const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
        this.editorCtx.insertText({
            text: formatDate
        })
    },
    insertImage() {
        const that = this
        wx.chooseImage({
            count: 1,
            success: function (res) {
                let data = {
                    url: res.tempFilePaths[0],
                    name: 'file',
                    formData: {},
                    isNew:true
                }
                that.insertDivider()
                http.uploadFlie(data, res1 => {
                    that.editorCtx.insertImage({
                        src: res1.data,
                        width: '100%',
                        success: function () {}
                    })
                }, err => {})

            }
        })
    },
    blur() {
        this.setData({
            showeditor: true
        })
        let _this = this;
        this.editorCtx.getContents({
            success(res) {
                _this.data.form.content=res.html
                console.log(_this.data.form)
            }
        })
        this.editorCtx.blur()
    },
    focus() {
        this.data.showeditor = false
        this.editorCtx.scrollIntoView()
        this.setData({
            showeditor: false
        })
    },
    aa() {},
    choosetime() {
        this.setData({
            datetime: !this.data.datetime
        })
    },
    choosedate(e) {
        let date = new Date(e.detail)
        // 备选方案
        // let date = e.detail
        this.setData({
            ['form.endTime']: formatTime1(date)
        })
        this.choosetime()
    },
    getLocation() {
        let _this = this;
        wx.chooseLocation({
            success(res) {
                console.log(res)
                _this.setData({
                    ['form.lat']: res.latitude,
                    ['form.lng']: res.longitude,
                    ['form.place']: res.address + ' ' + res.name
                })
            }
        })
    },
    verify() {
        let params = JSON.parse(JSON.stringify(this.data.form));
        if (this.data.loading) return;
        let _this = this;
        if (!this.data.checked) {
            wx.showToast({
                title: '请先同意协议',
                icon: "none"
            })
            return;
        }
       
        this.data.loading = true;
        //   if(!params.type) {
        //     wx.showToast({
        //       title: '类型不能为空',
        //       icon: "none"
        //     })
        //     return false;
        // } 

        if (!params.title) {
            wx.showToast({
                title: '标题不能为空',
                icon: "none"
            })
            this.data.loading = false;
            return false;
        }
        
        if (!params.place) {
            wx.showToast({
                title: '地址不能为空',
                icon: "none"
            })
            this.data.loading = false;
            return false;
        }
        if (!params.endTime) {
            wx.showToast({
                title: '时间不能为空',
                icon: "none"
            })
            this.data.loading = false;
            return false;
        }
        if (!params.contactPerson) {
            wx.showToast({
                title: '联系人不能为空',
                icon: "none"
            })
            this.data.loading = false;
            return false;
        }
        if (!params.telephoneNumber) {
            wx.showToast({
                title: '联系电话不能为空',
                icon: "none"
            })
            this.data.loading = false;
            return false;
        }
        if (!params.content) {
            wx.showToast({
                title: '详情不能为空',
                icon: "none"
            })
            this.data.loading = false;
            return false;
        }
        if (this.data.fileListImg.length > 0) {
            this.upDataFile(this.data.fileListImg, 0, 1);
            return false;
        } else if (this.data.fileListImg1.length > 0) {
            this.upDataFile(this.data.fileListImg1, 0, 1);
            return false;
        } else {
            this.setData({
                img1: [this.data.defaultImg]
            })
            this.submit()
        }
    },
    dingyue() {
        this.verify();
    },
    submit() {

        let params = JSON.parse(JSON.stringify(this.data.form));
        if(params.endTime.length<17){
            params.endTime = this.data.form.endTime + ":00"
        }
        params.images = this.data.img.join(',')
        // params.qrCode = this.data.img1.join(',')
        params.userId = getApp().globalData.userInfo.id
        let _this = this;
        _this.tijiao(params)
       

    },
    tijiao(params) {
        // wx.showLoading({
        //     mask: true
        // })
        var that = this;
        http.postExpressSave(params,
            function (res) {
                wx.hideLoading()
                if (res.code == 0) {
                    wx.showModal({
                        title: "提示",
                        content: "发布成功",
                        showCancel: false,
                        success: function () {
                            that.setData({
                                ['form.title']: '',
                                ['form.place']: '',
                                ['form.content']: '',
                                ['form.contactPerson']: '',
                                ['form.telephoneNumber']: '',
                                formshow: false,
                                fileListImg: [],
                                fileListImg1: [],
                                img: [],
                                img1: [],
                            })
                            wx.nextTick(_=>{
                                wx.navigateBack({
                                   delta:1 
                                })
                            })
                        },
                    })
                } else {
                    wx.showToast({
                        title: res.message,
                        icon: "none",
                    })
                    that.setData({
                        img: [],
                        img1: [],
                    })
                }
            },
            function (err) {
                that.setData({
                    img: [],
                    img1: [],
                })
                wx.hideLoading()
            })
        this.data.loading = false;
    },
    afterRead(event) {
        const {
            file
        } = event.detail;
        if (file.size > 5000000) {
            // 限制文件 5M以内
            wx.showToast({
                title: '文件过大，请重新选择',
                icon: "none"
            })
            return
        }
        if (file.type == "image") {
            file.isNew = true;
            this.setData({
                fileListImg: [...this.data.fileListImg, file],
            })
        } else {
            wx.showToast({
                title: '请上传图片文件',
            })
        }
    },
    afterRead1(event) {
        const {
            file
        } = event.detail;
        if (file.size > 5000000) {
            // 限制文件 5M以内
            wx.showToast({
                title: '文件过大，请重新选择',
                icon: "none"
            })
            return
        }
        if (file.type == "image") {
            file.isNew = true;
            this.setData({
                fileListImg1: [...this.data.fileListImg1, file],
            })
        } else {
            wx.showToast({
                title: '请上传图片文件',
            })
        }
    },
    upDataFile(data, index, type) {
        debugger
        let item = data[index];
        console.log("-----", item);
        var that = this;
        var p = {
            url: item.url,
            name: "file",
            formData: {},
            isNew:item.isNew
        }
        wx.showLoading({
            mask: true
        })
        http.upDataFile1(p,
            function (res) {
                console.log("---上传图片-", res);
                wx.hideLoading({
                    success: (res) => {},
                })
                if (res.code == 0) {
                    if (type == 1) {
                        that.data.img.push(res.data);
                        if (index == data.length - 1) {
                            if (that.data.fileListImg1.length > 0) {
                                that.upDataFile(that.data.fileListImg1, 0, 2)
                            } else {
                                // that.setData({
                                //     img1: [that.data.defaultImg]
                                // })
                                that.submit()
                            }
                        } else {
                            console.log("--继续执行--", index, data.length - 1);
                            that.upDataFile(data, index + 1, type)
                        }
                    } else if (type == 2) {
                        that.data.img1.push(res.data);
                        if (index == data.length - 1) {
                            that.submit()
                            that.data.loading = false;
                        }
                    } else {
                        wx.showToast({
                            title: res.message,
                            icon: "nene",
                        })
                        that.data.loading = false;
                    }
                }
            },
            function (err) {
                wx.hideLoading()
                that.data.loading = false;
            })
    },
    deletaImg: function (e) {
        //  console.log("-----",e);
        let index = e.detail.index;
        this.data.fileListImg.splice(index, 1);
        this.setData({
            fileListImg: this.data.fileListImg,
        })
    },
    deletaImg1: function (e) {
        //  console.log("-----",e);
        let index = e.detail.index;
        this.data.fileListImg1.splice(index, 1);
        this.setData({
            fileListImg1: this.data.fileListImg1,
        })
    },
    input: function (e) {
        input.bind(this)(e)
    },
    getDtl(id){
        wx.showLoading()
        let _this =this;
        http.postExpressInfo({id:id},res=>{
          if(res.code==0){
              let fileListImg=[]
            if(res.data.images){

              res.data.images.split(',').map(item=>{
                fileListImg.push({
                    url:item,
                    type:'image',
                    thumb:item
                  })
              })
            }
            this.setData({
              form:res.data,
              fileListImg
            })
            console.log(_this.data.fileListImg)
          }else{
            wx.showToast({
              title:'查询失败',
              icon:"none"
            })
          }
          wx.hideLoading()
        },err=>{
          wx.showToast({
            title:err,
            icon:"none"
          })
          wx.hideLoading()
        })
      },
      editorinput({detail}){
          this.setData({
              ['form.content']:detail.html
          })
      }
})